﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

namespace Jerkymon.Strings
{
    public class Utility
    {
		#region Static Methods (19)
		/// <summary>
        /// Filters a list of strings from another string. 
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <param name="s">Any number of strings to be filtered out.</param>
        /// <returns>The string, with the string s replaced by random nonsense characters.</returns>
        public static string ExplicitFilter(bool keepIfError, string mystring, params string[] s)
        {
            foreach (string z in s)
                mystring = ExplicitFilter(keepIfError, mystring, z);
            return mystring;
        }

		/// <summary>
        /// Filters a string from another string. 
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <param name="s">A string (character, word or words)</param>
        /// <returns>The string, with the string s replaced by random nonsense characters.</returns>
        public static string ExplicitFilter(bool keepIfError, string mystring, string s)
        {
            string oldstring = mystring;
            string start, end;
            bool explicit_filter = false;
            switch (s)
            {
                case "<":
                case ">":
                    start = "<";
                    end = ">";
                    break;
                case "{":
                case "}":
                    start = "{";
                    end = "}";
                    break;
                case "[":
                case "]":
                    start = "[";
                    end = "]";
                    break;
                case "(":
                case ")":
                    start = "(";
                    end = ")";
                    break;
                case "/*":
                case "*/":
                    start = "/*";
                    end = "*/";
                    break;
                case "//":
                    start = "//";
                    end = "\n";
                    break;
                case "///":
                    start = "///";
                    end = "\n";
                    break;
                default:
                    explicit_filter = true;
                    start = "nothing";
                    end = "nothing";
                    break;
            }
            if (explicit_filter)
            {
                string newword = "";
                string curses = "!@#$%^&*";
                Random random = new Random();
                for (int i = 0; i < s.Length; i++)
                    newword += curses[random.Next(curses.Length)];

                string lowerword = s.ToLower();
                string lowerstring = mystring.ToLower();
                while (lowerstring.IndexOf(lowerword) > -1)
                {
                    mystring = mystring.Substring(0, lowerstring.IndexOf(lowerword)) + newword + mystring.Substring(lowerstring.IndexOf(lowerword) + lowerword.Length);
                    lowerstring = lowerstring.Replace(lowerword, newword);
                }
                return mystring;
            }
            else
            {
                try
                {
                    while (mystring.IndexOf(start) != -1)
                    {
                        int startRemove = mystring.IndexOf(start);
                        mystring = mystring.Remove(startRemove, mystring.IndexOf(end) - startRemove + end.Length);
                        if (mystring.IndexOf(end) < mystring.IndexOf(start))
                            mystring = mystring.Remove(startRemove, mystring.IndexOf(end) - end.Length);
                    }
                }
                catch (Exception) // Swallow exception
                {
                    //throw new Ar
                    if (keepIfError)
                        return oldstring;
                    else
                        return "";
                }
                return mystring;
            }
        }

		public static void ExportToText(string buffer, string filename)
        {

            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";

            // set the response mime type for text
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\".txt");
            response.Write(buffer);
            response.Flush();
            response.Close();
            response.End();
        }

		/// <summary>
        /// Filters all braces and the content within [this stuff] from the string.
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <returns>The string, without the braced text.</returns>
        public static string FilterBraces(bool keepIfError, string mystring)
        {
            mystring = ExplicitFilter(keepIfError, mystring, "[");
            return mystring;
        }

		/// <summary>
        /// Filters all brackets and the content within {this stuff} from the string.
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <returns>The string, without the bracketed text.</returns>
        public static string FilterBrackets(bool keepIfError, string mystring)
        {
            mystring = ExplicitFilter(keepIfError, mystring, "{");
            return mystring;
        }

		/// <summary>
        /// Filters all comments of type ///, // or /**/ from the string. 
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <returns>The string, without the comments.</returns>
        public static string FilterComments(bool keepIfError, string mystring)
        {
            mystring = ExplicitFilter(keepIfError, mystring, "//", "/*", "///");
            return mystring;
        }

		/// <summary>
        /// Filters all angle bracket tags (a la HTML, XML or PHP) from the string.
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <returns>The string, without the markup tags.</returns>
        public static string FilterMarkupTags(bool keepIfError, string mystring)
        {
            mystring = ExplicitFilter(keepIfError, mystring, "<");
            return mystring;
        }

		/// <summary>
        /// Filters all angle parenthetical comments (this stuff) from the string.
        /// </summary>
        /// <param name="keepIfError">If this is set to true, and an error occurs, the method
        /// returns the original string.  Otherwise, it returns an empty string.</param>
        /// <param name="mystring">The string to be parsed.</param>
        /// <returns>The string, without the parenthetical comments.</returns>
        public static string FilterParentheses(bool keepIfError, string mystring)
        {
            mystring = ExplicitFilter(keepIfError, mystring, "(");
            return mystring;
        }

		public static string GetFromFile(string path)
        {
            string text2;
            try
            {
                StreamReader reader1 = new StreamReader(File.OpenRead(HttpContext.Current.Server.MapPath(path)));
                reader1.BaseStream.Seek((long)0, SeekOrigin.Begin);
                string text1 = reader1.ReadToEnd();
                reader1.Close();
                text2 = text1;
            }
            catch
            {
                try
                {
                    StreamReader reader1 = new StreamReader(File.OpenRead(path));
                    reader1.BaseStream.Seek((long)0, SeekOrigin.Begin);
                    string text1 = reader1.ReadToEnd();
                    reader1.Close();
                    text2 = text1;
                }
                catch
                {
                    text2 = "";
                }
            }
            return text2;
        }

		public static string Left(string param, int length)
        {
            return param.Substring(0, length);
        }

		public static string Mid(string param, int startIndex)
        {
            return param.Substring(startIndex);
        }

		public static string Mid(string param, int startIndex, int length)
        {
            return param.Substring(startIndex, length);
        }

		/// <summary>
        /// Replaces all occurrences of oldValue with newValue, ignoring the case of oldValue.
        /// </summary>
        /// <param name="mystring">The string to be parsed for replacement.</param>
        /// <param name="oldValue">A string to look for.  Case for this parameter does not matter.</param>
        /// <param name="newValue">A string to put in place.  Case for this parameter matters.</param>
        /// <returns>A string with the replaced words.</returns>
        public static string ReplaceIgnoreCase(string mystring, string oldValue, string newValue)
        {
            string lowerword = oldValue.ToLower();
            string lowerstring = mystring.ToLower();
            while (lowerstring.IndexOf(lowerword) > -1)
            {
                mystring = mystring.Substring(0, lowerstring.IndexOf(lowerword)) + newValue + mystring.Substring(lowerstring.IndexOf(lowerword) + lowerword.Length);
                lowerstring = lowerstring.Substring(0, lowerstring.IndexOf(lowerword)) + newValue + lowerstring.Substring(lowerstring.IndexOf(lowerword) + lowerword.Length);
            }
            return mystring;
        }

		/// <summary>
        /// Replaces a substring within a string with another substring with optional case sensitivity turned off.
        /// </summary>
        /// <param name="OrigString">String to do replacements on</param>
        /// <param name="FindString">The string to find</param>
        /// <param name="ReplaceString">The string to replace found string wiht</param>
        /// <param name="CaseInsensitive">If true case insensitive search is performed</param>
        /// <returns>updated string or original string if no matches</returns>
        public static string ReplaceString(string OrigString, string FindString,
                                           string ReplaceString, bool CaseInsensitive)
        {
            int at1 = 0;
            string newOrigString = string.Empty;

            while (true)
            {
                if (CaseInsensitive)
                    at1 = OrigString.IndexOf(FindString, at1, OrigString.Length - at1, StringComparison.OrdinalIgnoreCase);
                else
                    at1 = OrigString.IndexOf(FindString, at1);


                if (at1 == -1)
                    return OrigString;


                OrigString = OrigString.Substring(0, at1) + ReplaceString + OrigString.Substring(at1 + FindString.Length);

                at1 += ReplaceString.Length;

            }


            // return OrigString;

        }

		/// <summary>
        /// String replace function that support
        /// </summary>
        /// <param name="OrigString">Original input string</param>
        /// <param name="FindString">The string that is to be replaced</param>
        /// <param name="ReplaceWith">The replacement string</param>
        /// <param name="Instance">Instance of the FindString that is to be found. if Instance = -1 all are replaced</param>
        /// <param name="CaseInsensitive">Case insensitivity flag</param>
        /// <returns>updated string or original string if no matches</returns>
        public static string ReplaceStringInstance(string OrigString, string FindString,
                                                   string ReplaceWith, int Instance,
                                                   bool CaseInsensitive)
        {
            if (Instance == -1)
                return ReplaceString(OrigString, FindString, ReplaceWith, CaseInsensitive);
            int at1 = 0;
            for (int x = 0; x < Instance; x++)
            {
                if (CaseInsensitive)
                    at1 = OrigString.IndexOf(FindString, at1, OrigString.Length - at1, StringComparison.OrdinalIgnoreCase);
                else
                    at1 = OrigString.IndexOf(FindString, at1);

                if (at1 == -1)
                    return OrigString;

                if (x < Instance - 1)
                    at1 += FindString.Length;

            }

            return OrigString.Substring(0, at1) + ReplaceWith + OrigString.Substring(at1 + FindString.Length);

            //StringBuilder sb = new StringBuilder(OrigString); 
            //sb.Replace(FindString, ReplaceString, at1, FindString.Length); 
            //return sb.ToString();
        }

		public static string Right(string param, int length)
        {
            return param.Substring(param.Length - length, length);
        }

		public static string[] SplitByString(string testString, string split)
        {
            int num1 = 0;
            int num2 = 0;
            int[] numArray1 = new int[testString.Length + 1];
            while (num2 < testString.Length)
            {
                int num3 = testString.IndexOf(split, num2);
                if (num3 != -1)
                {
                    numArray1[num1++] = num3;
                    num2 = num3 + split.Length;
                }
                else
                {
                    num2 = testString.Length;
                }
            }
            string[] textArray1 = new string[num1 + 1];
            if (num1 == 0)
            {
                textArray1[0] = testString;
                return textArray1;
            }
            num1--;
            textArray1[0] = testString.Substring(0, numArray1[0]);
            for (int num4 = 0; num4 < num1; num4++)
            {
                textArray1[num4 + 1] = testString.Substring(numArray1[num4] + split.Length, (numArray1[num4 + 1] - numArray1[num4]) - split.Length);
            }
            textArray1[num1 + 1] = testString.Substring(numArray1[num1] + split.Length);
            return textArray1;
        }

		public static string TrimStringWithTillMeetSpace(string input, int size)
        {
            input = Regex.Replace(input, "<.+?>", "", RegexOptions.IgnoreCase);
            if (input.Length <= size)
            {
                return input;
            }
            string text = "";
            string[] textArray = input.Split(" ".ToCharArray());
            for (int i = 0; i < textArray.GetUpperBound(0); i++)
            {
                text = text + " " + textArray[i];
                if (text.Length > size)
                {
                    break;
                }
            }
            return (text + " ...");
        }

		public static void TxtToExcel(string sdata, string fileName)
        {

            HttpResponse response = HttpContext.Current.Response;

            // first let's clean up the response.object
            response.Clear();
            response.Charset = "";

            // set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

            //System.IO.StreamWriter excelDoc;

            using (StringWriter excelDoc = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(excelDoc))
                {
                    excelDoc.Write(sdata);
                    //excelDoc.Close();
                    response.Write(excelDoc.ToString());
                    response.Flush();
                    response.End();
                    response.Close();

                }
            }

            //response.Write(excelDoc.ToString());
            //response.End();

        }
		#endregion
    }



}
